package com.zonda.sampleretrofit2.data;

import android.os.Looper;
import android.util.Log;

import com.zonda.sampleretrofit2.Contants;
import com.zonda.sampleretrofit2.IOUtils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;

public final class AppNewsListApiClient {

  private final static AppNewsListApiClient INSTANCE = new AppNewsListApiClient();

  private final Retrofit mAppRetrofit;

  private final static String APP_BASE_URL = "http://121.9.213.58/iphone.myzaker.com/";

  private NewsListService mNewsListService;

  private AppNewsListApiClient() {

    final File dirFile = new File(IOUtils.getDirectory(Contants.LOG_TAG, Contants.APP_CONTEXT));
    //dirFile.mkdirs();
    final int cacheSize = 10 * 1024 * 1024;//10M
    final Cache cache = new Cache(dirFile, cacheSize);

    final OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
      @Override
      public Response intercept(Chain chain) throws IOException {
        final Request request = chain.request();
        Headers headers = request.headers();
        Log.i(Contants.LOG_TAG, "addInterceptor headers: " + headers.toString());
        final Response response = chain.proceed(request);
        Log.i(Contants.LOG_TAG, "addInterceptor response.code(): " + response.code() + " isMain: "
            + (Looper.getMainLooper() == Looper.myLooper()));
        return response;
      }
    }).addNetworkInterceptor(new Interceptor() {
      @Override
      public Response intercept(Chain chain) throws IOException {

        final Request request = chain.request();
        Headers headers = request.headers();
        Log.i(Contants.LOG_TAG, "addNetworkInterceptor headers: " + headers.toString());
        final Response response = chain.proceed(request);
        Log.i(Contants.LOG_TAG, "addNetworkInterceptor response.code(): " + response.code() + " isMain: "
            + (Looper.getMainLooper() == Looper.myLooper()));
        return response;
      }
    }).connectTimeout(10, TimeUnit.SECONDS).
        writeTimeout(10, TimeUnit.SECONDS).
        readTimeout(12, TimeUnit.SECONDS).
        cache(cache).
        build();

    mAppRetrofit = new Retrofit.Builder()
        .baseUrl(APP_BASE_URL)
        .addConverterFactory(AppConverterFactory.create())
        .client(okHttpClient)
        .build();
  }

  public static NewsListService getNewsListService() {
    return INSTANCE.createNewsListService();
  }

  private NewsListService createNewsListService() {

    if (mNewsListService == null) {
      mNewsListService = mAppRetrofit.create(NewsListService.class);
    }
    return mNewsListService;
  }
}
